import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
import i18n from '@/lang'
import { wxSdkRegister } from '@/utils/wxsdk'
import { getOfficalAccountAPI } from '@/api/wechat'
import { get1stHostName, getViewbox, getQueryObject } from '@/utils'
import { 
  wechatGetUnionidByCode
} from '@/wxLogin'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from) {
    const box = getViewbox()
    if (box) {
      setTimeout(() => {
        box.scrollTop = (to.meta.keepAlive && to.meta.scrollTop) ? to.meta.scrollTop : 0
      }, 200)
    }
  }
})

router.beforeEach((to, from, next) => {

  store.dispatch('setPageLoading', true)

  // set document title
  if (to.meta.title) {
    if (i18n.te('router.' + to.meta.title)) {
      document.title = i18n.t('router.' + to.meta.title)
    } else {
      document.title = i18n.t('siteTitle')
    }
  }

  // list scrollTop
  const box = getViewbox()
  if (box && from.meta.hasOwnProperty('scrollTop')) {
    from.meta.scrollTop = box ? box.scrollTop : 0
  }

  // remember first url when IOS device
  if (store.state.app.device === 'ios' && !store.state.app.iosJsUrl) {
    store.commit('SET_IOS_JS_URL', document.URL)
  }

  // 获取城市及用户信息相关信息
  if (!store.state.city.id || !store.state.userInfo.userProfile.fansId) {
    const hostname = get1stHostName()

    getOfficalAccountAPI({ name: hostname }).then(({ data }) => {

      store.commit('SET_CITY', data)

      // authorize页面独立处理
      if (to.name === 'authorize') {
        next()
        return
      }
      
      store.dispatch('getUserProfile').then(({ userProfile: profile }) => {
        
        const query = getQueryObject()
        if (!profile.hasUnionid && query.code && query.state) {
          wechatGetUnionidByCode(query)
          return
        }

        next()
      })
    })

    return
  }

  next()
})

router.afterEach((to, from) => {
  store.dispatch('setPageLoading', false)

  // 一个页面jssdk只需注册一次，无需重复注册，这样可以减少流量
  if (!to.meta.isJssdkConfig) {
    // hack for ios device
    let redirectUrl = window.location.origin + to.fullPath
    if (store.state.app.device === 'ios') {
      redirectUrl = store.state.app.iosJsUrl
    }

    wxSdkRegister('/api/jssdk/', redirectUrl, [
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'chooseWXPay',
      'hideMenuItems',
      'chooseImage',
      'previewImage'
    ], (result) => {
      if (result) {
        console.log(to.name + ', %cweixin jssdk config success', 'color: green;')
        to.meta.isJssdkConfig = true
      } else {
        to.meta.isJssdkConfig = false
      }
    })
  }
})

export default router
